package com.aspirecn.core.datacache;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import com.aspirecn.core.commons.StringUtils;
import org.apache.log4j.Logger;

import com.aspire.core.match.ua.object.*;//大量引用，不好挪动
import com.aspirecn.core.commons.Configuration;
import com.aspirecn.core.commons.Constant;

/**
 * UA缓存，通联数据
 * 
 * @author wangxinning
 * 
 */
public class UACache extends BaseLocalCache {

	public final static Logger logger = Logger.getLogger(UACache.class);
	public static Logger faillog = Logger.getLogger("uacenter");// 比较特殊，记录适配失败的UA，需要同步出去

	private static UACache instance = new UACache();

	// android特殊适配数据，两个地方有定义，另一个在load
	//public static Integer[] android_deviceids = Constant.android_deviceids;
	
	public int getDeviceKeyWordCount()
	{
		return this.m_DeviceKeywordList.size();
	}
	
	public List<DeviceKeyword> getDeviceKeywordList()
	{
		return this.m_DeviceKeywordList;
	}
	
	public int getDeviceCount()
	{
		return this.m_DeviceList.size();
	}
	
	//全匹配，调试用
	public List<Device> matchUAForDebug( String ua )
	{
		List<Device> retList = new ArrayList<Device>();
		for( DeviceKeyword keyword:m_DeviceKeywordList )
		{
			String[] keywords = new String[]{keyword.getKeyword1(),keyword.getKeyword2(),keyword.getKeyword3()};
			keywords = ArrayUtils.removeElement(keywords, "?");
			keywords = ArrayUtils.removeElement(keywords, "%");			
			
			if(StringUtils.containsArrayIgnoreCase(ua, keywords))//全部包含
			{
				Device device = this.getDevice(keyword.getDevice_id());
				
				if( device != null )
				{
					retList.add(device);
				}				
			}
		}
		
		return retList;
	}

	private UACache() {
		
		//调试时可以修改路径
		String path = System.getProperty("ua.data.path");
		if( StringUtils.isBlank(path) )
		{
			path = Configuration.getInstance()
					.getDownloadFilePath();
		}
		
		this.dataFile = new File(path
				+ (StringUtils.endsWith(path, File.separator) ? ""
						: File.separator) + "ua.json");
		
		load();
	}

	public static UACache getInstance() {
		return instance;
	}

	//************************************数据加载部分
	@Override
	public void load() {
		//避免同时load
		if ( !loading.getAndSet(true) && Configuration.getInstance().switchUACache() && this.dataFile.exists()) {
			
			long start = System.currentTimeMillis();
			long startMem = Runtime.getRuntime().freeMemory();

			try {

				this.clear();

				String contentString = FileUtils.readFileToString(
						this.dataFile, "gbk");

				if (Configuration.getInstance().isMM()) {
					loadFilterDevice(StringUtils.substringBetween(
							contentString, "<!--FilterDevice-->"));
				}

				loadDeviceKeyword(StringUtils.substringBetween(contentString,
						"<!--DeviceKeyWord-->"));
				loadDevice(StringUtils.substringBetween(contentString,
						"<!--Device-->"));
				loadDeviceBrand(StringUtils.substringBetween(contentString,
						"<!--DeviceBrand-->"));
				loadDeviceGWUA(StringUtils.substringBetween(contentString,
						"<!--DeviceGWUA-->"));
				loadDeviceUA(StringUtils.substringBetween(contentString,
						"<!--DeviceUA-->"));
				loadDeviceOS(StringUtils.substringBetween(contentString,
						"<!--DeviceOS-->"));
				loadSeries(StringUtils.substringBetween(contentString,
						"<!--DeviceSeries-->"));
				
			} catch (Exception e) {
				loading.set(false);
				logger.error("UA数据加载失败", e);
				return;
			}

			loading.set(false);
			long end = System.currentTimeMillis();
			long endMem = Runtime.getRuntime().freeMemory();
			updateFileDownloadTime();
			logger.info("UA信息加载完成，time=" + (end - start) + "ms,占用内存="
					+ (endMem - startMem) / FileUtils.ONE_KB + "kb");

		} else {
			logger.info("配置关闭，UA信息未加载");
		}
		
		loading.set(false);
	}

	@Override
	public void clear() {
		m_DeviceList.clear();
		m_DeviceMap.clear();
		m_DeviceBrandMap.clear();
		m_DeviceBrandList.clear();
		m_CalDeviceKeywordMap.clear();
		m_DeviceKeyword1List.clear();
		m_DeviceGWUAList.clear();
		m_DeviceKeywordList.clear();
		m_DeviceUAMap.clear();
		m_DeviceOSMap.clear();
		m_FilterDeviceMap.clear();
		m_SeriesMap.clear();
		m_deviceKeywordIDMap.clear();
	}
	
	
	public Map<Integer, DeviceOS> getDeviceOSMap()
	{
		return this.m_DeviceOSMap;
	}
	

	public List<DeviceGWUA> getDeviceGWUAList()
	{
		return m_DeviceGWUAList;
	}
	
	@Override
	public void reload() {

		if (this.fileIsChange()) {
			this.clear();
			this.load();
		} else {
			logger.info("没变化，UA信息未加载");
		}
	}

	private List<Device> m_DeviceList = new ArrayList<Device>();
	private Map<Integer, Device> m_DeviceMap = new HashMap<Integer, Device>();

	public void addDevice(Device device) {
		
		if (!m_FilterDeviceMap.isEmpty()
				&& this.m_FilterDeviceMap.get(device.getDevice_id()) == null) {
			
			return;
		}

		// 2012-08-14 add 无法适配的不加载 10-10 增加android通用版
		if (this.m_deviceKeywordIDMap.get(device.getDevice_id()) == null
				&& !ArrayUtils.contains(Constant.android_deviceids,
						device.getDevice_id())) {
			
			return;
		}
		
		m_DeviceList.add(device);
		m_DeviceMap.put(device.getDevice_id(), device);
	}

	public Device getDevice(int device_id) {
		Device retDevice = m_DeviceMap.get(device_id);
		if (retDevice != null) {
			retDevice.setDeviceOS(this.getDeviceOS(retDevice.getOs_id()));
			retDevice.setSeries(this.getSeries(retDevice.getSeries_id()));
		}

		List<DeviceUA> deviceUAList = this.m_DeviceUAMap.get(device_id);
		if (deviceUAList != null && !deviceUAList.isEmpty()
				&& retDevice != null) {
			DeviceUA deviceUA = deviceUAList.get(0);
			retDevice.setDevice_ua(deviceUA.getDevice_ua());
			retDevice.setDevice_os_ua(deviceUA.getDevice_os_ua());
		}
		return retDevice;
	}

	public List<Device> getDeviceList() {
		return m_DeviceList;
	}

	public List<Device> getDeviceListByBrandID(int brandid) {
		Iterator<Device> ite = this.m_DeviceList.iterator();

		List<Device> retList = new ArrayList<Device>();
		while (ite.hasNext()) {
			Device device = ite.next();
			if (device.getBrand_id() == brandid) {
				retList.add(device);
			}
		}

		return retList;
	}

	private Map<Integer, DeviceBrand> m_DeviceBrandMap = new HashMap<Integer, DeviceBrand>();
	private List<DeviceBrand> m_DeviceBrandList = new ArrayList<DeviceBrand>();

	public void addDeviceBrand(DeviceBrand deviceBrand) {
		m_DeviceBrandList.add(deviceBrand);
		m_DeviceBrandMap.put(deviceBrand.getBrand_id(), deviceBrand);
	}

	public List<DeviceBrand> getDeviceBrandList() {
		return m_DeviceBrandList;
	}

	public DeviceBrand getDeviceBrand(int brand_id) {
		return m_DeviceBrandMap.get(brand_id);
	}

	private List<DeviceGWUA> m_DeviceGWUAList = new ArrayList<DeviceGWUA>();

	public void addDeviceGWUA(DeviceGWUA deviceGWUA) {

		if (!m_FilterDeviceMap.isEmpty()
				&& this.m_FilterDeviceMap.get(deviceGWUA.getDevice_id()) == null) {
			return;
		}

		m_DeviceGWUAList.add(deviceGWUA);
	}

	private List<DeviceKeyword> m_DeviceKeywordList = new ArrayList<DeviceKeyword>();

	public List<String> getDeviceKeyword1List() {
		return m_DeviceKeyword1List;
	}

	private Map<String, List<DeviceKeyword>> m_CalDeviceKeywordMap = new HashMap<String, List<DeviceKeyword>>();
	private List<String> m_DeviceKeyword1List = new ArrayList<String>();
	// 2012-08-14 过滤无法适配的Device用
	private Map<Integer, String> m_deviceKeywordIDMap = new HashMap<Integer, String>();

	public void addDeviceKeyword(DeviceKeyword deviceKeyword) {

		if (!m_FilterDeviceMap.isEmpty()
				&& this.m_FilterDeviceMap.get(deviceKeyword.getDevice_id()) == null) {
			return;
		}

		m_deviceKeywordIDMap.put(deviceKeyword.getDevice_id(), "1");
		m_DeviceKeywordList.add(deviceKeyword);

		List<DeviceKeyword> calList = m_CalDeviceKeywordMap.get(deviceKeyword
				.getKeyword1());
		if (calList == null) {
			calList = new ArrayList<DeviceKeyword>();
			m_CalDeviceKeywordMap.put(deviceKeyword.getKeyword1(), calList);
		}
		calList.add(deviceKeyword);

		if (!m_DeviceKeyword1List.contains(deviceKeyword.getKeyword1())) {
			m_DeviceKeyword1List.add(deviceKeyword.getKeyword1());
		}
	}

	public List<DeviceKeyword> getDeviceKeywordList(String keyword1) {
		return m_CalDeviceKeywordMap.get(keyword1);
	}

	private Map<Integer, List<DeviceUA>> m_DeviceUAMap = new HashMap<Integer, List<DeviceUA>>();

	public void addDeviceUA(DeviceUA deviceUA) {

		if (!m_FilterDeviceMap.isEmpty()
				&& this.m_FilterDeviceMap.get(deviceUA.getDevice_id()) == null) {
			return;
		}

		List<DeviceUA> calList = m_DeviceUAMap.get(deviceUA.getDevice_id());
		if (calList == null) {
			calList = new ArrayList<DeviceUA>();
			m_DeviceUAMap.put(deviceUA.getDevice_id(), calList);
		}
		calList.add(deviceUA);

	}

	public Map<Integer, List<DeviceUA>> getDeviceUAMap() {
		return m_DeviceUAMap;
	}

	private Map<Integer, DeviceOS> m_DeviceOSMap = new HashMap<Integer, DeviceOS>();

	public void addDeviceOS(DeviceOS deviceOS) {
		m_DeviceOSMap.put(deviceOS.getOs_id(), deviceOS);
	}

	public DeviceOS getDeviceOS(int os_id) {
		return m_DeviceOSMap.get(os_id);
	}

	private Map<Integer, FilterDevice> m_FilterDeviceMap = new HashMap<Integer, FilterDevice>();

	public Map<Integer, FilterDevice> getFilterDeviceMap() {
		return m_FilterDeviceMap;
	}
	
	public void addFilterDevice(FilterDevice filterDevice) {
		m_FilterDeviceMap.put(filterDevice.getFulldeviceid(), filterDevice);
	}

	public FilterDevice getFilterDevice(int device_id) {
		return m_FilterDeviceMap.get(device_id);
	}

	private Map<Integer, Series> m_SeriesMap = new HashMap<Integer, Series>();

	public void addSeries(Series series) {
		m_SeriesMap.put(series.getSeries_id(), series);
	}

	public Series getSeries(int series_id) {
		return m_SeriesMap.get(series_id);
	}
	
	public Map<Integer, Series> getSeriesMap() {
		return m_SeriesMap;
	}

	public boolean isEmpty() {
		return m_DeviceList.isEmpty() && m_DeviceMap.isEmpty()
				&& m_DeviceBrandMap.isEmpty() && m_DeviceGWUAList.isEmpty()
				&& m_DeviceKeywordList.isEmpty() && m_DeviceUAMap.isEmpty()
				&& m_DeviceOSMap.isEmpty() && m_FilterDeviceMap.isEmpty()
				&& m_SeriesMap.isEmpty();
	}

	private void loadDevice(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addDevice(JSONToObjectUtils.toDevice(jsonobj));
		}

		logger.debug("load Device over!(" + this.m_DeviceList.size() + ")");
	}

	private void loadDeviceBrand(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addDeviceBrand(JSONToObjectUtils.toDeviceBrand(jsonobj));
		}

		logger.debug("load DeviceBrand over!(" + this.m_DeviceBrandMap.size()
				+ ")");
	}

	private void loadDeviceGWUA(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addDeviceGWUA(JSONToObjectUtils.toDeviceGWUA(jsonobj));
		}

		logger.debug("load DeviceGWUA over!(" + this.m_DeviceGWUAList.size()
				+ ")");
	}

	private void loadDeviceKeyword(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addDeviceKeyword(JSONToObjectUtils.toDeviceKeyword(jsonobj));
		}

		logger.debug("load DeviceKeyword1 over!("
				+ this.m_DeviceKeyword1List.size() + ")");
		logger.debug("load DeviceKeyword over!("
				+ this.m_DeviceKeywordList.size() + ")");
	}

	private void loadDeviceUA(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addDeviceUA(JSONToObjectUtils.toDeviceUA(jsonobj));
		}

		logger.debug("load DeviceUA over!(" + this.m_DeviceUAMap.size() + ")");
	}

	private void loadDeviceOS(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addDeviceOS(JSONToObjectUtils.toDeviceOS(jsonobj));
		}

		logger.debug("load DeviceOS over!(" + this.m_DeviceOSMap.size() + ")");
	}

	private void loadFilterDevice(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addFilterDevice(JSONToObjectUtils.toFilterDevice(jsonobj));
		}

		logger.debug("load FilterDevice over!(" + this.m_FilterDeviceMap.size()
				+ ")");
	}

	private void loadSeries(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);

		ListIterator<?> ite = jsonArray.listIterator();
		while (ite.hasNext()) {
			String objstr = ite.next().toString();
			JSONObject jsonobj = JSONObject.fromObject(objstr);
			this.addSeries(JSONToObjectUtils.toSeries(jsonobj));
		}

		logger.debug("load Series over!(" + this.m_SeriesMap.size() + ")");
	}

	// ***********************************从开始到这里，上面是数据加载部分，一般不用动

	// ***********************************下面到结束，数据操作部分
	public DeviceBrand getBrand(int brandID) {
		if (this.isLoading()) {
			return null;
		}
		return this.getDeviceBrand(brandID);
	}

	// 匹配android的方法，8-24号新需求提出
	private Device matchAndroidUA(String ua) {

		if (this.isLoading()) {
			return null;
		}

		Device retDevice = null;
		if (StringUtils.containsIgnoreCase(ua, "android")) {
			if (StringUtils.containsIgnoreCase(ua, "1.5")) {
				retDevice = getDevice(Constant.android_deviceids[0]);
			} else if (StringUtils.containsIgnoreCase(ua, "1.6")) {
				retDevice = getDevice(Constant.android_deviceids[1]);
			} else if (StringUtils.containsIgnoreCase(ua, "2.0")) {
				retDevice = getDevice(Constant.android_deviceids[2]);
			} else {
				retDevice = getDevice(Constant.android_deviceids[3]);
			}
		}

		return retDevice;
	}

	public List<DeviceBrand> searchBrand(String keyword) {

		if (this.isLoading()) {
			return null;
		}

		List<DeviceBrand> list = new ArrayList<DeviceBrand>();
		for (int i = 0; i < this.getDeviceBrandList().size(); i++) {
			DeviceBrand deviceBrand = this.getDeviceBrandList().get(i);
			if (StringUtils.containsIgnoreCase(deviceBrand.toString(), keyword)) {
				list.add(deviceBrand);
			}
		}

		return list;
	}

	public List<Device> searchDevice(String keyword) {

		if (this.isLoading()) {
			return null;
		}

		List<Device> list = new ArrayList<Device>();
		String filters = "|";// 避免重复
		for (int i = 0; i < this.getDeviceList().size(); i++) {
			Device device = this.getDeviceList().get(i);
			if ((StringUtils.containsIgnoreCase(device.getDevice_name(),
					keyword) || StringUtils.containsIgnoreCase(
					device.getDevice_desc(), keyword))
					&& !StringUtils
							.contains(
									filters,
									"|"
											+ Integer.toString(device
													.getDevice_id()) + "|")) {
				list.add(device);
				filters += Integer.toString(device.getDevice_id()) + "|";
			}
		}

		return list;
	}

	public List<Device> searchDevice(int brandid, String keyword) {

		if (this.isLoading()) {
			return null;
		}

		List<Device> list = searchDevice(keyword);

		if (list != null && !list.isEmpty()) {
			Iterator<Device> ite = list.iterator();
			while (ite.hasNext()) {
				Device device = ite.next();

				if (device.getBrand_id() != brandid) {
					ite.remove();
				}
			}
		}

		return list;
	}

	public List<Device> getBrandDeviceList(int brandID) {

		if (this.isLoading()) {
			return null;
		}

		Iterator<Device> ite = this.getDeviceList().iterator();

		List<Device> retList = new ArrayList<Device>();
		while (ite.hasNext()) {
			Device device = ite.next();
			if (device.getBrand_id() == brandID && this.checkDevice(device)) {
				retList.add(device);
			}
		}

		if (retList.isEmpty()) {
			retList = null;
		}

		return retList;
	}

	public Device matchUA(String ua) {

		if (this.isLoading()) {
			return null;
		}

		long start = System.currentTimeMillis();

		if (StringUtils.isEmpty(ua)) {
			return null;
		}

		// 曾经做过同样匹配并且匹配失败
		if (isNoMatchUA(ua)) {
			// faillog.error("不可匹配UA：" + ua);
			return null;
		}

		// 曾经做过同样匹配并且匹配成功
		if (isMatchUA(ua)) {
			// log.info("缓存中获取UA：" + ua);
			return (Device) this.matchMap.get(ua);
		}

		int timeslog = 0;

		Iterator<String> ite1 = this.getDeviceKeyword1List().iterator();

		while (ite1.hasNext()) {

			timeslog++;

			String key = ite1.next();

			if (isIncludeInUA(ua, key)) {
				List<DeviceKeyword> list = this.getDeviceKeywordList(key);

				for (int i = 0; i < list.size(); i++) {

					timeslog++;

					DeviceKeyword dk = list.get(i);

					// 垃圾方法，？和%不会匹配的临时措施，会改
					if (StringUtils.containsIgnoreCase(dk.getKeyword2(), "?")) {
						dk.setKeyword2(key);
					}
					if (StringUtils.containsIgnoreCase(dk.getKeyword2(), "%")) {
						dk.setKeyword2(key);
					}
					if (StringUtils.containsIgnoreCase(dk.getKeyword3(), "?")) {
						dk.setKeyword3(key);
					}
					if (StringUtils.containsIgnoreCase(dk.getKeyword3(), "%")) {
						dk.setKeyword3(key);
					}

					if (isIncludeInUA(ua, dk.getKeyword1())
							&& isIncludeInUA(ua, dk.getKeyword2())
							&& isIncludeInUA(ua, dk.getKeyword3())) {

						long end = System.currentTimeMillis();
						logger.debug("匹配次数:" + timeslog + ";ua:" + ua + ";规则:"
								+ dk + "(" + (end - start) + "ms!)");

						Device retDevice = this.getDevice(dk.getDevice_id());

						// 可能会出现适配到deviceid，但是没有相应对象的情况,11-4修改
						if (retDevice != null) {

							addMatchUA(ua, retDevice);

							logger.debug(ua + "====" + retDevice.getDevice_id()
									+ "====" + retDevice.getDevice_desc());
							return retDevice;
						}
					}
				}
			}
		}

		long end = System.currentTimeMillis();
		logger.debug("匹配次数：" + timeslog + ",根据资源库适配失败(" + (end - start)
				+ "ms!)");

		/**
		 * 如果匹配不到，引入android判断方法再次匹配
		 * 
		 */
		Device androidDevice = matchAndroidUA(ua);
		// android匹配成功
		if (androidDevice != null) {
			addMatchUA(ua, androidDevice);

			logger.debug(ua + "====" + androidDevice.getDevice_id() + "===="
					+ androidDevice.getDevice_desc());
			return androidDevice;
		}

		addNoMatchUA(ua);
		return null;
	}

	// 判断UA中是否包含关键字符串
	private boolean isIncludeInUA(String ua, String searchStr) {
		// 在android字符串中的做如下判断，因为mot的有一个适配有问题
		if (searchStr != null && searchStr.length() < "android2".length()
				&& StringUtils.containsIgnoreCase("android2", searchStr)) {
			return false;
		}

		if (searchStr != null && searchStr.length() < "android 2".length()
				&& StringUtils.containsIgnoreCase("android 2", searchStr)) {
			return false;
		}

		String[] tezhengArray = null;
		tezhengArray = (String[]) ArrayUtils.add(tezhengArray, searchStr);

		for (String tezheng : tezhengArray) {
			if (StringUtils.containsIgnoreCase(ua, tezheng)) {
				return true;
			}
		}

		return false;
	}

	private boolean checkDevice(Device device) {
		if (device == null) {
			return false;
		}

		if (StringUtils.contains(device.getDevice_desc(), "重复")) {
			return false;
		}

		return true;
	}

	public List<String> getBrandAlphaList(int brandID) {

		if (this.isLoading()) {
			return null;
		}

		logger.debug("getBrandAlphaList brandID=" + brandID);
		List<Device> uaList = this.getDeviceListByBrandID(brandID);

		if (uaList != null && !uaList.isEmpty()) {
			List<String> retList = new ArrayList<String>();
			Map<String, String> filterMap = new HashMap<String, String>();

			for (int i = 0; i < uaList.size(); i++) {
				if (filterMap.get(uaList.get(i).getDevice_first_alpha()) == null) {
					retList.add(uaList.get(i).getDevice_first_alpha());
					filterMap.put(uaList.get(i).getDevice_first_alpha(), "1");
				}
			}

			logger.debug("getBrandAlphaList result:" + retList);
			return retList;
		} else {
			return null;
		}
	}

	public List<Device> getBrandAlphaDeviceList(int brandID, String firstAlpha) {

		if (this.isLoading()) {
			return null;
		}

		List<Device> uaList = this.getDeviceListByBrandID(brandID);

		if (uaList != null && !uaList.isEmpty()) {
			List<Device> retList = new ArrayList<Device>();

			for (int i = 0; i < uaList.size(); i++) {
				if (StringUtils.equals(uaList.get(i).getDevice_first_alpha(),
						firstAlpha) && checkDevice(uaList.get(i))) {
					retList.add(uaList.get(i));
				}
			}

			return retList;
		} else {
			return null;
		}
	}

	public String formatUA(String ua) {
		Device device = this.matchUA(ua);

		if (device != null) {
			if (StringUtils.isNotEmpty(device.getEnglish_device_name())) {
				return device.getEnglish_device_name();
			} else {
				return device.getDevice_name();
			}
		} else {
			return ua;
		}
	}

	// 无法匹配的UA临时缓存
	private Map<String, String> noMatchMap = new ConcurrentHashMap<String, String>();
	// 可以匹配的UA临时缓存
	private Map<String, Device> matchMap = new ConcurrentHashMap<String, Device>();

	private void addNoMatchUA(String ua) {
		if (this.noMatchMap.size() >= 3000) {
			this.noMatchMap.clear();
		}

		faillog.error("不可匹配UA：" + ua);
		this.noMatchMap.put(ua, "1");
	}

	private void addMatchUA(String ua, Device device) {
		if (this.matchMap.size() >= 5000) {
			this.matchMap.clear();
		}

		this.matchMap.put(ua, device);
	}

	private boolean isNoMatchUA(String ua) {
		if (this.noMatchMap.get(ua) == null) {
			return false;
		} else {
			return true;
		}
	}

	private boolean isMatchUA(String ua) {
		if (this.matchMap.get(StringUtils.trimToEmpty(ua)) == null) {
			return false;
		} else {
			return true;
		}
	}
	// ***********************************数据操作部分结束	
	
	public static void main(String[] args) {
		UACache uaCache = UACache.getInstance();
//		//uaCache.reload();
//
//		String ua = "S100_TD/1.0 Android/4.0 Tiger/1.0 Release/02.02.2013 Browser/AppleWebKit534.3 Profile/NULL Configuration/NULL";
//		System.out.println(ua);
//		System.out.println(uaCache.matchUA(ua));
//		
		String ua = "MASTONE g18";
		System.out.println(ArrayUtils.toString( Constant.android_deviceids ));
		System.out.println(uaCache.matchUA(ua));
		System.out.println(ArrayUtils.toString( Constant.android_deviceids ));
//		System.out.println(RequestUtil);
//		
//		Integer[] android_deviceids = new Integer[] { 9402, 9403,
//				9404, 9030 };
//		System.out.println(ArrayUtils.contains(android_deviceids, 9405));
	}
}
